package com.example.demo.cimfrontroute.service.impl;

import com.example.demo.cim.common.pojo.CIMUserInfo;
import com.example.demo.cimfrontroute.service.UserInfoCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.example.demo.cimfrontroute.constant.Constant.ACCOUNT_PREFIX;
import static com.example.demo.cimfrontroute.constant.Constant.LOGIN_STATUS_PREFIX;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2019-01-13
 **/
@Service
public class UserInfoCacheServiceImpl implements UserInfoCacheService {


    /**
     * 本地缓存，为了防止内存撑爆，后期可换为 LRU。
     */
    private final static Map<Long,CIMUserInfo> USER_INFO_MAP = new ConcurrentHashMap<>(64) ;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean saveAndCheckUserLoginStatus(Long userId) throws Exception {
        Long add = redisTemplate.opsForSet().add(LOGIN_STATUS_PREFIX, userId.toString());
        if (add == 0) {
            return false;
        } else{
            return true;
        }
    }

    @Override
    public CIMUserInfo loadUserInfoByUserId(Long userId) {
        //优先从本地缓存获取
        CIMUserInfo cimUserInfo = USER_INFO_MAP.get(userId);
        if(cimUserInfo!=null) {
            return cimUserInfo;
        }

        //load redis
        String sendUserName = redisTemplate.opsForValue().get(ACCOUNT_PREFIX + userId);
        if (sendUserName != null) {
            cimUserInfo = new CIMUserInfo(userId, sendUserName);
            USER_INFO_MAP.put(userId, cimUserInfo);
        }
        return cimUserInfo;
    }
}



